﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public enum toolStatu
{
    inBase, //候选框底
    inCandidate, //可拖动
    inPlan //放地板上了
}
public class toolOne : DragUI, IPointerClickHandler, IPointerEnterHandler
{
    bool hasInit = false;
    string recycleType;
    bool canDrag = false;
    public toolData data;//配置数据
    public saveToolData saveData;//需要保存的数据
    public List<Vector2> arrOffectPos;//占用格数
    Image img;
    RectTransform imgRect;
    Image onChooseImg;
    public List<bgCubeOne> arrPlanOne = new List<bgCubeOne>(); //用于记录
    float initWidth = 98;//单格宽度
    bool isHouXuan; //是否是在候选，候选不允许改变方向
    float size;
    Text tipName; //提示名字
    Text countTxt; //右上角数字
    GameObject countObj; //右上角数字
    toolStatu toolStatu;
    public void init(int id, saveToolData saveData, Transform parent, string recycleType, toolStatu toolStatu)
    {
        if (!hasInit)
        {
            hasInit = true;
            this.recycleType = recycleType;
            img = transform.Find("img").GetComponent<Image>();
            imgRect = img.GetComponent<RectTransform>();
            tipName = img.transform.GetComponentInChildren<Text>();
            onChooseImg = transform.Find("onChoose").GetComponent<Image>();
            countObj = transform.Find("count").gameObject;
            countTxt = countObj.transform.Find("count").GetComponent<Text>();
            initWidth = img.GetComponent<RectTransform>().rect.width;
        }
        transform.SetParent(parent, false);
        img.transform.localPosition = Vector3.zero;
        onChooseImg.gameObject.SetActive(false);
        initData();
        data = MyJson.config.toolData[id];
        this.saveData = saveData;
        setArrOffectPos();
        countObj.SetActive(false);
        tipName.gameObject.SetActive(false);
        size = GetComponent<RectTransform>().rect.width;
        changeImg();
        imgRect.sizeDelta = new Vector2(initWidth, initWidth);
        this.toolStatu = toolStatu;
        switch (toolStatu)
        {
            case toolStatu.inBase: //底部候选方块，不让拖拽
                creatorNew(id);
                canDrag = false;
                img.transform.localEulerAngles = Vector3.zero;
                isHouXuan = false;
                break;
            case toolStatu.inCandidate:
                canDrag = true;
                transform.localPosition = Vector3.zero;
                transform.localEulerAngles = Vector3.zero;
                isHouXuan = true;
                countObj.SetActive(data.hasCount);
                countTxt.text = "0";
                break;
            case toolStatu.inPlan:
                canDrag = true;
                transform.localPosition = (saveData.pos + arrOffectPos[0]) * 100;
                isHouXuan = false;
                refreshScale();
                arrPlanOne = getArrPlan();
                arrPlanOne.ForEach(one =>
                {
                    one.onPlace(this);
                });
                changeRotation(saveData.dir);
                countObj.SetActive(data.hasCount);
                countTxt.text = saveData.count.ToString();
                changScale(saveData.sx, saveData.sy);
                break;
        }
    }
    public void setArrOffectPos()
    {
        arrOffectPos = new List<Vector2>();
        switch (data.occupy)
        { //暂时先这样，后续开放到配置
            case "1":
                arrOffectPos.Add(Vector3.zero);
                break;
            case "2":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(0f, -1f, 0));
                break;
            case "2-h":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(-1f, 0f, 0));
                break;
            case "3":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(0f, -1f, 0));
                arrOffectPos.Add(new Vector3(0f, -2f, 0));
                break;
            case "4":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(1f, 0f, 0));
                arrOffectPos.Add(new Vector3(0f, -1f, 0));
                arrOffectPos.Add(new Vector3(1f, -1f, 0));
                break;
            case "6":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(1f, 0f, 0));
                arrOffectPos.Add(new Vector3(0f, -1f, 0));
                arrOffectPos.Add(new Vector3(1f, -1f, 0));
                arrOffectPos.Add(new Vector3(0f, -2f, 0));
                arrOffectPos.Add(new Vector3(1f, -2f, 0));
                break;
            case "8":
                arrOffectPos.Add(new Vector3(0f, 0f, 0));
                arrOffectPos.Add(new Vector3(1f, 0f, 0));
                arrOffectPos.Add(new Vector3(0f, -1f, 0));
                arrOffectPos.Add(new Vector3(1f, -1f, 0));
                arrOffectPos.Add(new Vector3(0f, -2f, 0));
                arrOffectPos.Add(new Vector3(1f, -2f, 0));
                arrOffectPos.Add(new Vector3(0f, -3f, 0));
                arrOffectPos.Add(new Vector3(1f, -3f, 0));
                break;
            default:
                arrOffectPos.Add(Vector3.zero);
                break;
        }
    }
    public void changeImg()
    {
        Sprite sp = Resources.Load<Sprite>("tool/" + data.img);
        if (sp != null)
        {
            img.sprite = sp;
            tipName.text = data.name;
            tipName.gameObject.SetActive(Global.gameData.isShowToolText);
        }
        else
        {
            img.sprite = null;
            tipName.text = data.name;
            tipName.gameObject.SetActive(true);
            string colorStr = "#" + MD5Str.MD5(data.name).Substring(0, 6);
            Color newColor;
            ColorUtility.TryParseHtmlString(colorStr, out newColor);
            img.color = newColor;
        }
        img.SetNativeSize();
    }
    public void refreshScale()
    {
        switch (data.occupy)
        { //暂时先这样，后续开放到配置
            case "2":
                imgRect.sizeDelta = new Vector2(initWidth, initWidth * 2);
                img.transform.localPosition = new Vector3(0, -0.5f, 0) * size;
                break;
            case "2-h":
                imgRect.sizeDelta = new Vector2(initWidth * 2, initWidth);
                img.transform.localPosition = new Vector3(-0.5f, 0, 0) * size;
                break;
            case "3":
                imgRect.sizeDelta = new Vector2(initWidth * 2, initWidth * 2);
                img.transform.localPosition = new Vector3(0, -1f, 0) * size;
                break;
            case "4":
                imgRect.sizeDelta = new Vector2(initWidth * 2, initWidth * 2);
                img.transform.localPosition = new Vector3(0.5f, -0.5f, 0) * size;
                break;
            case "6":
                imgRect.sizeDelta = new Vector2(initWidth * 2, initWidth * 3);
                img.transform.localPosition = new Vector3(0.5f, -1f, 0) * size;
                break;
            case "8":
                imgRect.sizeDelta = new Vector2(initWidth * 2, initWidth * 4);
                img.transform.localPosition = new Vector3(0.5f, -1.5f, 0) * size;
                break;
        }
    }
    public override void OnDrag(PointerEventData eventData)
    {
        if (!canDrag)
        {
            return;
        }
        if (Input.GetMouseButton(1))
        { //现在右键按下是批量删除
            return;
        }
        base.OnDrag(eventData);
        arrPlanOne.ForEach(one =>
        {
            one.onUnTip();
            one.onRemoveCube(data);
        });
        if (checkPlaced())
        {
            arrPlanOne.ForEach(one =>
            {
                one.onTip(data.img);
            });
        }
    }
    //检测是否可放置
    public bool checkPlaced(Vector3? localAngles = null)
    {
        localAngles = localAngles == null ? transform.localEulerAngles : localAngles;
        arrPlanOne = new List<bgCubeOne>();
        for (int i = 0; i < arrOffectPos.Count; i++)
        {
            Vector3 offsetPOne = arrOffectPos[i];
            offsetPOne = Quaternion.Euler((Vector3)localAngles) * offsetPOne;
            Vector3 childP = offsetPOne * size + transform.localPosition;
            bool oneIsOk = false;
            for (int j = 0; j < Global.GameProxy.arrBgCubeOne.Count; j++)
            {
                oneIsOk = Global.GameProxy.arrBgCubeOne[j].checkPosIsOk(childP, data);
                if (oneIsOk)
                {
                    arrPlanOne.Add(Global.GameProxy.arrBgCubeOne[j]);
                    break;
                }
            }
            if (!oneIsOk)
            {
                return false;
            }
        }
        return true;
    }
    public override void OnBeginDrag(PointerEventData eventData)
    {
        if (!canDrag)
        {
            return;
        }
        refreshScale();
        base.OnBeginDrag(eventData);
        Global.GameProxy.hasToolDraging = true;
        //从父类表面再生成一个候选
        if (isHouXuan)
        {
            toolOne parentCom = transform.parent.GetComponent<toolOne>();
            parentCom.creatorNew(data.id);
            isHouXuan = false;
        }
        transform.SetParent(Global.GameProxy.ControlBox.content, false);
        initData();
    }
    public override void OnEndDrag(PointerEventData eventData)
    {
        if (!canDrag)
        {
            return;
        }
        base.OnEndDrag(eventData);
        Global.GameProxy.hasToolDraging = false;
        arrPlanOne.ForEach(one =>
        {
            one.onUnTip();
        });
        if (arrPlanOne.Count == arrOffectPos.Count)
        { //可放置
            toolStatu = toolStatu.inPlan;
            OnPointerClick(null);
            Vector3 p = arrPlanOne[0].transform.localPosition;
            transform.localPosition = new Vector2(p.x, p.y) - arrOffectPos[0] * size;
            transform.SetParent(Global.GameProxy.ControlBox.getAndCreatorLevel(data.zIndex));
            arrPlanOne.ForEach(one =>
            {
                one.onPlace(this);
            });
            saveData.pos = arrPlanOne[0].dataPos;
            Global.GameProxy.saveData();
        }
        else
        {
            recycling();
        }

    }
    public void OnPointerClick(PointerEventData eventData)
    {
        if (Global.GameProxy.copyToolOne != null)
        {
            Global.GameProxy.copyToolOne.unChoose();
        }
        Global.GameProxy.copyToolOne = this;
        if (toolStatu == toolStatu.inPlan)
        {
            Global.GameProxy.ControlBox.anctionControl(data, this);
            onChoose();
        }
    }
    //创建一个新的道具候选区
    public void creatorNew(int id)
    {
        GameObject newChild = Global.GameProxy.ControlBox.getPrefabByName(prefabType.toolOne);
        newChild.GetComponent<toolOne>().init(id, new saveToolData() { id = data.id }, transform, recycleType, toolStatu.inCandidate);
    }
    public void recycling()
    {
        List<bgCubeOne> arrPlan = getArrPlan();
        arrPlan.ForEach(one =>
        {
            one.onRemoveCube(data);
        });
        Global.GameProxy.ControlBox.pushPrefabByName(recycleType, gameObject);
    }
    //修改方向
    public void changeRotation(int? dir)
    {
        if (isHouXuan)
        {
            return;
        }
        if (dir == null)
        {
            transform.localEulerAngles = Vector3.zero;
            return;
        }
        Vector3 rotation = Vector3.zero;
        saveData.dir = dir;
        switch (dir)
        {
            case 1:
                rotation = new Vector3(0, 0, 0);
                break;
            case 2:
                rotation = new Vector3(0, 0, 270);
                break;
            case 3:
                rotation = new Vector3(0, 0, 180);
                break;
            case 4:
                rotation = new Vector3(0, 0, 90);
                break;
        }
        getArrPlan().ForEach(one =>
        {
            one.onRemoveCube(data);
        });
        bool canRotation = checkPlaced(rotation);
        if (canRotation)
        {
            transform.localEulerAngles = rotation;
            arrPlanOne.ForEach(one =>
            {
                one.onPlace(this);
            });
        }
        else
        {
            getArrPlan().ForEach(one =>
            {
                one.onPlace(this);
            });
        }
    }
    //修改数量
    public void changeCount(int count)
    {
        if (isHouXuan)
        {
            return;
        }
        saveData.count = count;
        countTxt.text = count.ToString();
    }
    //修改缩放方向
    public void changScale(int? sx, int? sy)
    {
        if (isHouXuan)
        {
            return;
        }
        if (sx != null)
        {
            saveData.sx = sx;
        }
        if (sy != null)
        {
            saveData.sy = sy;
        }
        transform.localScale = new Vector3((sx == null || sx == 0) ? 1 : (int)sx, (sy == null || sy == 0) ? 1 : (int)sy, 1);
    }
    //获取底板
    public List<bgCubeOne> getArrPlan()
    {
        List<bgCubeOne> arrPlan = new List<bgCubeOne>();
        arrOffectPos.ForEach(one =>
        {
            Vector3 offsetPOne = Quaternion.Euler(transform.localEulerAngles) * one;
            Vector2 offectP = new Vector2(offsetPOne.x, offsetPOne.y) + saveData.pos;
            bgCubeOne plan = Global.GameProxy.arrBgCubeOne.Find(planOne =>
            {
                return Vector2.Equals(offectP, planOne.dataPos);
            });
            if (plan != null)
            {
                arrPlan.Add(plan);
            }
            // else {
            //     Debug.LogError ("未找到对应底板");
            // }
        });
        return arrPlan;
    }
    //批量删除
    public void OnPointerEnter(PointerEventData eventData)
    {
        if (Input.GetMouseButton(1))
        {
            recycling();
        }
    }
    //当被选中
    public void onChoose()
    {
        onChooseImg.gameObject.SetActive(true);
    }
    //取消被选中
    public void unChoose()
    {
        onChooseImg.gameObject.SetActive(false);
    }
}